/**
 * Created by fwj on 16-01-18.
 */
$(function () {
    //-----------------------验证
    //var step =1;
    var ids = $("#ids").val();
    $('#modal-wizard-container')
        .ace_wizard({
            //step: 1 //optional argument. wizard will jump to step "2" at first
            //buttons: '.wizard-actions:eq(0)'
        })
        .on('actionclicked.fu.wizard', function (e, info) {
            var operate = $("#operate").val();
            if (operate == 'add') {
                if (info.step == 1) {
                    if (!$('#clusterUser').valid()) e.preventDefault();
                    findClientquota();


                }
                if (info.step == 2) {
                    //在第二步的时候，选择上一步无需选择集群 update20170718qinfengxia
                    if(info.direction == "next"){
                        if (!$('#kerbers_form').valid()) e.preventDefault();
                    }

                    //var clientHome = $("#clientHome").val();
                    //$('#select').append("<option value='"+ this.id+"'>"+ this.name +"</option>");
                }
                if (info.step == 3) {
                    var hp_username = $("#userName").val().replace(/(^\s*)|(\s*$)/g, "");
                    var count = parseInt($("ul li:last input").val());
                    for (var i = 0; i < count; i++) {
                        var index = i + 1;
                        if (index == 1) {
                            $("#queue" + index + "").find("input[name='queueName']").val(hp_username );
                            $("#queue" + index + "").find("input[name='acl']").val(hp_username );
                        } else {
                            $("#queue" + index + "").find("input[name='queueName']").val(hp_username + "_" + index);
                            $("#queue" + index + "").find("input[name='acl']").val(hp_username );
                        }
                    }
                }
            }
            else{
                if (info.step == 1) {
                    findClientquota();
                }
            }
        })
        .on('finished.fu.wizard', function (e) {
            var operate = $("#operate").val();
            if (operate == 'add') {
                //----------------------租户配置
                var userName = $("#userName").val().replace(/(^\s*)|(\s*$)/g, "");
                var clientPW = $("#clientPW").val();
                var contactPerson = $("#contactPerson").val();
                var phoneNumber = $("#phoneNumber").val();
                var email = $("#email").val();
                var userTypeId = $("#userTypeId").val();
                var companyId = $("#companyId").val();
                var remark = $("#remark").val();
                var itsmNumber = $("#itsmNumber").val();
                var clusterTypeId = $("#clusterTypeId").val();
                var clusterUser = '{"userName":"' + userName + '","clientPW":"' + clientPW + '","contactPerson":"' + contactPerson + '","phoneNumber":"' + phoneNumber + '","email":"' + email + '","userTypeId":"' + userTypeId + '","remark":"' + remark + '","companyId":"' + companyId + '","clusterTypeId":' + clusterTypeId + ',"itsmNumber":"' + itsmNumber + '"}'
                //----------------kerbers配置
                var days = $("#days").val();
                var status =$("#status:checked").val();
                if(status=='on'){
                    status=0;//0为成功
                }else{
                    status=1;//1为不成功
                }
                var machineId = document.getElementsByName("machineId");
                var machineIds = [];
                var machineClientQuotaList = "";
                for (var i = 0; i < machineId.length; i++) {
                    if (machineId[i].checked) {
                        machineIds.push(machineId[i].value);
                        var clientCatalog = $("#kerbers_tr_"+machineId[i].value).find("select[id='clientCatalog']").val();
                        var clientCatalogSize = $("#kerbers_tr_"+machineId[i].value).find("input[id='clientCatalogSize']").val();
                        var clientCatalogUnit = $("#kerbers_tr_"+machineId[i].value).find("select[id='clientCatalogUnit']").val();
                        if(clientCatalogSize == ""){
                            clientCatalogSize=0;
                        }
                        var client = '{"machineId":' + machineId[i].value + ',"clientCatalog":"' + clientCatalog + '", "clientCatalogSize":' + clientCatalogSize + ', "clientCatalogUnit":"' + clientCatalogUnit + '"}';
                        machineClientQuotaList += client + ";";
                    }
                }
                //----------------HDFS配置
                var hdfsSpace = $("#hdfsSpace").val();
                var hdfsFileCount = $("#hdfsFileCount").val();
                var hdfsSpaceUnit = $("#hdfsSpaceUnit").val();
                if(hdfsSpace==""){
                    hdfsSpace=null;
                }
                if(hdfsFileCount==""){
                    hdfsFileCount=null;
                }
                var hdfs = "";
                if (hdfsSpace != null || hdfsFileCount != null) {
                    hdfs = '{"hdfsSpace":' + hdfsSpace + ',"hdfsFileCount":' + hdfsFileCount + ',"hdfsSpaceUnit":"' + hdfsSpaceUnit + '"}';
                }
                //-----------------------MR配置
                var count = parseInt($("ul li:last input").val());
                var queueList = "";
                var queue = "";
                var queryList = [];
                //根据companyId(租户id)获取租户信息add20160714qinfengxia
                var surplusResource = 0;//当前租户剩余资源
                var surplusCpu = 0;//当前租户剩余cpu
                var companyId = $("#companyId option:selected").val();
                if(companyId != null && companyId != ""){
                    $.ajax({
                        url: "findCompanyParams.do",
                        data: "companyId=" + companyId ,
                        type: "post",
                        dataType: "json",
                        async:false,
                        success: function (data) {
                            if(data != null && data != ""){
                                surplusResource = data.surplusResource;
                                if(surplusResource<0){
                                    surplusResource = data.companyMaxResource;
                                }
                                surplusCpu = data.surplusCpu;
                                if(surplusCpu <0){
                                    surplusCpu = data.companyMaxCpu;
                                }
                            }
                        },
                        error: function () {
                            alert("error");
                            return false;
                        }

                    })
                }
                for (var i = 0; i < count; i++) {
                    var index = i + 1;
                    var queueName = $("#queue" + index + "").find("input[name=queueName]").val();
                    if (queueName == "") {
                        $("#queue" + index + "").find("input[name='queueName']").css("border", "#B35D5D solid 1px");
                        alert("请填写检查队列配置MR_" + index);
                        return false;
                    } else {
                        $("#queue" + index + "").find("input[name='queueName']").css("border", "1px solid #d8dcde");
                    }
                    var minResource = $("#queue" + index + "").find("input[name=minResource]").val();
                    if (minResource == "") {
                        $("#queue" + index + "").find("input[name='minResource']").css("border", "#B35D5D solid 1px");
                        alert("请填写检查队列配置MR_" + index);
                        return false;
                    } else {
                        $("#queue" + index + "").find("input[name='minResource']").css("border", "1px solid #d8dcde");
                    }
                    var minCpu = $("#queue" + index + "").find("input[name=minCpu]").val();
                    if (minCpu == "") {
                        $("#queue" + index + "").find("input[name='minCpu']").css("border", "#B35D5D solid 1px");
                        alert("请填写检查队列配置MR_" + index);
                        return false;
                    } else {
                        $("#queue" + index + "").find("input[name='minCpu']").css("border", "1px solid #d8dcde");
                    }
                    var maxResource = $("#queue" + index + "").find("input[name=maxResource]").val();
                    if (maxResource == "") {
                        $("#queue" + index + "").find("input[name='maxResource']").css("border", "#B35D5D solid 1px");
                        alert("请填写检查队列配置MR_" + index);
                        return false;
                    } else {
                        $("#queue" + index + "").find("input[name='maxResource']").css("border", "1px solid #d8dcde");
                    }
                    var maxCpu = $("#queue" + index + "").find("input[name=maxCpu]").val();
                    if (maxCpu == "") {
                        $("#queue" + index + "").find("input[name='maxCpu']").css("border", "#B35D5D solid 1px");
                        alert("请填写检查队列配置MR_" + index);
                        return false;
                    } else {
                        $("#queue" + index + "").find("input[name='maxCpu']").css("border", "1px solid #d8dcde");
                    }
                    var maxApp = $("#queue" + index + "").find("input[name=maxApp]").val();
                    if (maxApp == "") {
                        $("#queue" + index + "").find("input[name='maxApp']").css("border", "#B35D5D solid 1px");
                        alert("请填写检查队列配置MR_" + index);
                        return false;
                    } else {
                        $("#queue" + index + "").find("input[name='maxApp']").css("border", "1px solid #d8dcde");
                    }
                    var weight = $("#queue" + index + "").find("input[name=weight]").val();
                    if (weight == "") {
                        $("#queue" + index + "").find("input[name='weight']").css("border", "#B35D5D solid 1px");
                        alert("请填写检查队列配置MR_" + index);
                        return false;
                    } else {
                        $("#queue" + index + "").find("input[name='weight']").css("border", "1px solid #d8dcde");
                    }
                    if (parseInt(minResource) > parseInt(maxResource)) {
                        alert("请填写检查队列配置MR_" + index + "最小资源不能大于最大资源数");
                        return false;
                    }
                    if (parseInt(minCpu) > parseInt(maxCpu)) {
                        alert("请填写检查队列配置MR_" + index + "最小资源CPU不能大于最大资源CPU数");
                        return false;
                    }
                    //校验当前填写的maxResource是否大于当前租户剩余resource  add20160714qinfengxia
                    if(parseInt(maxResource) > parseInt(surplusResource)){
                        alert("请填写检查队列配置MR_" + index + "最大资源不能大于当前租户剩余资源（剩余:"+surplusResource+")");
                        return false;
                    }
                    //校验当前填写的maxCpu是否大于当前租户剩余cpu  add20160714qinfengxia
                    if (parseInt(maxCpu) > parseInt(surplusCpu)) {
                        alert("请填写检查队列配置MR_" + index + "最大资源CPU数不能大于当前租户剩余资源CPU数（剩余:"+surplusCpu+")");
                        return false;
                    }
                    var acl = $("#queue" + index + "").find("input[name=acl]").val();
                    queue = '{"queueName":"' + queueName + '","minResource":' + minResource + ',"minCpu":' + minCpu + ',"maxApp":' + maxApp + ',"weight":' + weight + ',"maxResource":' + maxResource + ',"maxCpu":' + maxCpu + ',"acl":"' + acl + '"}';
                    queueList += queue + ";";
                    queryList.push(queueName);
                }
                if (checkArrayRepeat(queryList)) {
                    alert("队列名称有重复的,请重新填写!");
                    return false;
                }
                var startTime=0;
                var endTime =0;
                if($("#start").val()!='永久'){
                   startTime = $("#start").val() ;
                }
                if($("#end").val()!='永久'){
                   endTime =  $("#end").val();
                }

                $.ajax({
                    type: 'post',
                    url: "save_clusterUser.do",
                    dataType: "json",
                    timeout:0,
                    data: {
                        "sclusterUser": clusterUser,
                        "shdfs": hdfs,
                        "validDay": days,
                        "status":status,
                        "machineIds": machineIds.toString(),
                        "squeueList": queueList.toString(),
                        "start":startTime,
                        "end":endTime,
                        "machineClientQuotaList":machineClientQuotaList.toString()
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(textStatus);
                    },
                    success: function (data) {
                        if (data.success) {
                            var message = data.data.message;
                            console.log(message);
                            if (data.data.type == 'error') {
                                var message = data.data.message;
                                layer.open({
                                    title: '提示信息',
                                    content: message,
                                    maxWidth: 630
                                });
                            } else {
                                var message = message.replace(/, /g, '<br/>');
                                layer.config({
                                    extend: ['skin/moon/style.css'] //加载新皮肤
                                });
                                layer.open({
                                    title: '提示信息',
                                    area: ['630px', '500px'],
                                    content: message,
                                    extend: ['skin/moon/style.css'],
                                    skin: 'layer-ext-moon',
                                    yes: function (index) {
                                        window.location.reload();
                                        layer.close();
                                    },
                                    cancel: function(index){
                                        window.location.reload();
                                        layer.close();
                                    }
                                });
                            }
                        } else {
                        }
                    }
                });

            }else{
                window.location.reload();
                layer.close();
            }

        }).on('stepclick.fu.wizard', function (e) {
            //e.preventDefault();//this will prevent clicking and selecting steps
        });
    if (ids.indexOf(",") > 0) {
        $('#modal-wizard').wizard('selectedItem', {
            step: 1
        });
    }
    jQuery.validator.addMethod("clientPW", function (value, element) {
        var flag =  /((?=.*[a-z])(?=.*\d)|(?=.*[a-z])(?=.*\d)(?=.*[#@!~%^&*]))[a-z\d#@!~%^&*]{6,18}/i.test(value);
        return this.optional(element) || flag;
    }, "<span style='color:red;'>必须包含字母和数字，可包含特殊字符（#@!~%^&*）</span>");
    jQuery.validator.addMethod("mobile", function (value, element) {
        //var reg = new RegExp("((?=[\x21-\x7e]+)[^A-Za-z0-9])");
        var flag = /^[1][0-9][0-9]{9}$/.test(value);
        return this.optional(element) || flag;
    }, "<span style='color:red;'>请填写正确的手机号码!</span>");
    $('#clusterUser').validate({
        errorElement: 'div',
        errorClass: 'help-block',
        focusInvalid: false,
        ignore: "",
        rules: {
            userName: {
                required: true
            },
            clientPW: {
                required: true,
                minlength: 6,
                clientPW: 'required'
            },
            contactPerson: {
                required: true
            },
            phoneNumber: {
                required: true
            },
            email: {
                required: true,
                maxlength:30,
                email:true
            }
        },
        messages: {
            userName: {
                required: "<span style='color:red;'>客户名称必填!</span>"
            },
            clientPW: {
                required: "<span style='color:red;'>请输入客户机密码!</span>",
                clientPW:"<span style='color:red;float:left;margin-left:50px;'>必须包含字母和数字，可包含特殊字符（#@!~%^&*）</span>",
                minlength: "<span style='color:red;'>请输入6~18位的客户机密码!</span>"
            },
            contactPerson: {
                required: "<span style='color:red;'>联系人必填!</span>"
            },
            phoneNumber: {
                required: "<span style='color:red;'>联系方式必填!</span>"
            },
            email: {
                required: "<span style='color:red;'>邮箱必填!</span>",
                email: "<span style='color:red;'>请输入有效的邮箱格式!</span>",
                maxlength:"<span style='color:red;'>邮箱长度过长!</span>"
            }
        },
        highlight: function (e) {
            $(e).closest('.form-group').removeClass('has-info').addClass('has-error');
        },
        success: function (e) {
            $(e).closest('.form-group').removeClass('has-error');//.addClass('has-info');
            $(e).remove();
        },
        errorPlacement: function (error, element) {
            if (element.is('input[type=checkbox]') || element.is('input[type=radio]')) {
                var controls = element.closest('div[class*="col-"]');
                if (controls.find(':checkbox,:radio').length > 1) controls.append(error);
                else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0));
            }
            else if (element.is('.select2')) {
                error.insertAfter(element.siblings('[class*="select2-container"]:eq(0)'));
            }
            else if (element.is('.chosen-select')) {
                error.insertAfter(element.siblings('[class*="chosen-container"]:eq(0)'));
            }
            else error.insertAfter(element.parent());
        },

        submitHandler: function (form) {
        },
        invalidHandler: function (form) {
        }
    });
    //-------------------kerbers
    $('#kerbers_form').validate({
        errorElement: 'div',
        errorClass: 'help-block',
        focusInvalid: false,
        ignore: "",
        rules: {
            days: {
                required: true
            },
            kerberid: {
                required: true
            }
        },
        messages: {
            days: {
                required: "<span style='color:red;'>有效期必填!</span>"
            },
            kerberid: {
                required: "<span style='color:red;'>请至少选择一个机器!</span>"
            }
        },
        highlight: function (e) {
            $(e).closest('.form-group').removeClass('has-info').addClass('has-error');
        },
        success: function (e) {
            $(e).closest('.form-group').removeClass('has-error');//.addClass('has-info');
            $(e).remove();
        },
        errorPlacement: function (error, element) {
            if (element.is('input[type=checkbox]') || element.is('input[type=radio]')) {
                var controls = element.closest('div[class*="col-"]');
                if (controls.find(':checkbox,:radio').length > 1) controls.append(error);
                else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0));
            }
            else if (element.is('.select2')) {
                error.insertAfter(element.siblings('[class*="select2-container"]:eq(0)'));
            }
            else if (element.is('.chosen-select')) {
                error.insertAfter(element.siblings('[class*="chosen-container"]:eq(0)'));
            }
            else error.insertAfter(element.parent());
        },

        submitHandler: function (form) {
        },
        invalidHandler: function (form) {
        }
    });

    //kerbers集群选中所有的机器
    $("#checkAll").click(function () {
        if (this.checked) {
            $("input[name='machineId']:checkbox").each(function () { //遍历所有的name为selectFlag的 checkbox
                $(this).prop("checked", true);
            })
            var machineId = document.getElementsByName("machineId");
            var machineIds = [];
            for (var i = 0; i < machineId.length; i++) {
                if (machineId[i].checked) {
                    machineIds.push(machineId[i].value);
                }
            }
            $("#kerberid").val(machineId.toString());
        } else {   //反之 取消全选
            $("input[name='machineId']:checkbox").each(function () { //遍历所有的name为selectFlag的 checkbox
                $(this).prop("checked", false);
                //alert("f");
            })
            $("#kerberid").val("");
        }
    });

    var companyId = $("#companyId_set").val();
    if (companyId != '') {
        $("#companyId").val(companyId);
    }
    var userTypeId_set = $("#userTypeId_set").val();
    if (userTypeId_set != '') {
        $("#userTypeId").val(userTypeId_set);
    }
    var clusterTypeId_set = $("#clusterTypeId_set").val();
    if (clusterTypeId_set != '') {
        $("#clusterTypeId").val(clusterTypeId_set);
    }
    var remark_set = $("#remark_set").val();
    if (remark_set != ''||remark_set!=null) {
        $("#remark").html(remark_set);
    }
    if(remark_set==null||remark_set==null){
        $("#remark").val('');
    }

    var operate = $("#operate").val();
    if (operate == 'add') {
        $("#userName").val('');
        $("#clientPW").val('');
    }
})

function last() {
    return false;
}

function findClientquota(){

    //修改界面，给用户目录设置默认值update20160824
    var hp_username = $("#userName").val().replace(/(^\s*)|(\s*$)/g, "");
    $.ajax({
        url: "findClientHome.do",
        data: "userName=" + hp_username ,
        type: "post",
        dataType: "json",
        async:false,
        success: function (data) {
            if(data != null && data != ""){
                $("td[id*='catalog_td']").each(function(){
                    var tdThis = $(this);
                    tdThis.find("select[id='clientCatalog']").each(function(){
                        if(tdThis.parent().find("input[id='machineId']").attr("checked") && tdThis.parent().find("input[id='clientquotaId']") !=null && tdThis.parent().find("input[id='clientquotaId']")!=""){
                            $(this).append("<option value='"+tdThis.parent().find("input[id='clientCatalogHidden']").val()+"'>"+tdThis.parent().find("input[id='clientCatalogHidden']").val()+"</option>");
                        }else{
                            $(this).empty();
                            for( i=0;i<data.length;i++){
                                $(this).append("<option value='"+data[i]+"'>"+data[i]+"</option>");
                            }
                        }
                    });
                });
            }
        },
        error: function () {
        }
    })
}